import axios from "axios";
import { showMessage } from "./status"; // 引入状态码文件
import { ElMessage } from "element-plus"; // 引入el 提示框，
import { useI18n } from "vue-i18n";




// 设置接口超时时间
axios.defaults.timeout = 60000*10;


// @ts-ignore
axios.defaults.baseURL = import.meta.env.VITE_API_DOMAIN;

//http request 拦截器
// axios.interceptors.request.use(
//   (config) => {
//     // 配置请求头
//     config.headers = {
//       "Content-Type": "application/json;charset=UTF-8",
//       "Authorization": import.meta.env.DEV ? "zijin" :'', //55 56
//     };
   
//     return config;
//   },
//   (error) => {
//     return Promise.reject(error);
//   }
// );

//http response 拦截器
axios.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    const { response } = error;
    if (response) {

      showMessage(response.status);
      return Promise.reject(response.data);
    } else {
      const { t } = useI18n();
      let networkConnectionAbnormality = t('message.networkConnectionAbnormality')
      ElMessage.warning(networkConnectionAbnormality);
    }
  }
);

// 封装 GET POST 请求并导出
export function request(
  url = "",
  params = {},
  type = "GET",
  headers: any = "json"
) {
  //设置 url params type 的默认值
  if (url.indexOf("/en") > -1) {
    let shopCurrency =  localStorage.getItem("shopCurrency")
    if (shopCurrency == null){
      shopCurrency = "/en"
    }else{
      shopCurrency = "/"+ shopCurrency
    }
    url = url.replace(
      "/en",
      shopCurrency
    );
  }

  if (type == "GET" || type == "get") {

    headers = {
      "Content-Type": "application/json;charset=UTF-8",
      "Authorization": import.meta.env.DEV ? "zijin" :'', //55 56
    };
  } else if (type == "POST" || type == "post") {
    headers = {
      "Content-Type": "multipart/form-data",
      "Authorization": import.meta.env.DEV ? "zijin" :'', //55 56
    };
  }
  return new Promise((resolve, reject) => {
    console.log(headers)
    let promise: any = "";
    if (type.toUpperCase() === "GET") {
      promise = axios({
        headers,
        url,
        params,
      });
    } else if (type.toUpperCase() === "POST") {
      console.log({
        headers,
        method: "POST",
        url,
        data: params,
      })
      promise = axios({
        headers,
        method: "POST",
        url,
        data: params,
      });
    }
    //处理返回
    promise
      .then((res: any) => {
        resolve(res);
      })
      .catch((err: any) => {
        reject(err);
      });
  });
}
